package org.springside.examples.showcase.utilities.wb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import org.springside.modules.utils.Encodes;
import org.springside.modules.utils.HttpUtils;

/**
 * A example that demonstrates how HttpClient APIs can be used to perform form-based logon.
 */
public class SinaLoginSha1 {
	private static Logger log = Logger.getLogger(SinaLoginSha1.class);
	private static String cookie = null;

	public static void main(String[] args) throws Exception {
		// 20120926@zyl 新浪cookie失效
		// SUE=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT;SUP=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT;ALF=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT;ALC=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT;SUR=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT;SSOLoginState=deleted;
		// expires=Thu, 01-Jan-1970 00:00:01 GMT;
		System.out.println("==============" + getCookieRealTime("work4041x@sina.com", "work123456"));
	}

	/**
	 * 得到登录新浪后的cookie
	 * 
	 * @return
	 */
	public static String getCookieRealTime(String uid, String pwd) {
		uid = Encodes.encodeBase64(URLEncoder.encode(uid).getBytes());
		System.out.println("uid:" + uid);
		try {
			// 封装需要post的参数
			String servertime = getServerTime();
			System.out.println("servertime:" + servertime);
			String nonce = makeNonce(6);
			System.out.println("nonce:" + nonce);

			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("service", "sso"));
			nvps.add(new BasicNameValuePair("pwencode", "wsse"));
			nvps.add(new BasicNameValuePair("callback", "parent.sinaSSOController.loginCallBack"));
			nvps.add(new BasicNameValuePair("entry", "account"));
			nvps.add(new BasicNameValuePair("gateway", "1"));
			nvps.add(new BasicNameValuePair("nonce", nonce)); // 用于生成密码
			nvps.add(new BasicNameValuePair("gateway", "1"));
			nvps.add(new BasicNameValuePair("returntype", "IFRAME"));
			nvps.add(new BasicNameValuePair("savestate", "0"));
			nvps.add(new BasicNameValuePair("encoding", "UTF-8"));
			nvps.add(new BasicNameValuePair("servertime", servertime)); // 用于生成密码
			nvps.add(new BasicNameValuePair("setdomain", "1"));
			nvps.add(new BasicNameValuePair("useticket", "0"));
			nvps.add(new BasicNameValuePair("vsnf", "1"));
			String password = new SinaEncoder().encode(pwd, servertime, nonce);
			System.out.println("password:" + password);
			nvps.add(new BasicNameValuePair("sp", password)); // 密码
			nvps.add(new BasicNameValuePair("su", uid)); // 用户名

			// 模拟http协议
			List<String> headers = new ArrayList<String>();
			headers.add("Accept:text/html, application/xhtml+xml, */*");
			headers.add("Accept-Language:zh-cn");
			headers.add("Connection:Keep-Alive");
			headers.add("Content-Type:application/x-www-form-urlencoded");
			headers.add("Host:login.sina.com.cn");
			headers.add("Referer:http://login.sina.com.cn/signup/signin.php");
			headers.add("User-Agent:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)");
			HttpUtils httpUtils = new HttpUtils("login.sina.com.cn", 80, 60000, 60000, headers);
			List reqResult = httpUtils.doRequest("POST", "/sso/login.php?client=ssologin.js(v1.3.17)", new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			Header[] _headers = (Header[]) reqResult.get(0);
			cookie = HttpUtils.getCookie(_headers);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// httpclient.getConnectionManager().shutdown();
		}
		File cookieFile = new File(System.getProperty("user.dir") + "/conf/cookie.txt");
		try {
			OutputStream output = new FileOutputStream(cookieFile);
			IOUtils.write(cookie, output, "UTF-8");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return cookie;
	}

	public static String getCookie() {
		if (cookie == null) {
			getCookieFromFile();
		}
		if (cookie == null) {
			getCookieRealTime("work4041x@sina.com", "work123456");
			System.out.println("=============" + cookie + "===========");
		}
		return cookie;
	}

	private static void getCookieFromFile() {
		try {
			File cookieFile = new File(System.getProperty("user.dir") + "/conf/cookie.txt");
			if (cookieFile.exists()) {
				cookie = FileUtils.readFileToString(cookieFile, "UTF-8");
			} else {
				cookieFile.createNewFile();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String makeNonce(int len) {
		String x = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String str = "";
		for (int i = 0; i < len; i++) {
			str += x.charAt((int) (Math.ceil(Math.random() * 1000000) % x.length()));
		}
		return str;
	}

	private static String getServerTime() {
		long servertime = new Date().getTime() / 1000;
		return String.valueOf(servertime);
	}
}
